# !/Scripts/python
# coding=utf-8
# @Author       : Inky
# @Date         : 2020-06-10 23:03:03
# @LastEditTime : 2020-06-10 23:03:14
# @FilePath     : /inky-ws/decision_algorithm/msf/StateMachine.py
# @Description  : FSM-Learning

class InitializationError(Exception):
    pass

class StateMachine:
    '''
    选择结构实现简单有限状态机
    '''
    positive_adj = ["great", "super", "fun", "entertainint", "easy"]
    negative_adj = ["boring", "difficult", "ugly", "bad"]
    def __init__(self):
        self.handler = {}
        self.startState = None
        self.endState = []

    def add_state(self, name, handler, end_state=0):
        name = name.lower()
        self.handler[name] = handler
        if end_state:
            self.endState.append(name)

    def set_start(self, name):
        self.startState = name.lower()

    def run(self, cargo):
        try:
            handler = self.handler[self.startState]
        except:
            raise InitializationError("Must call .set_start() before .run()")
        if not self.endState:
            raise InitializationError("At least one state must be specified to be endState.")

        while(True):
            (newState, cargo) = handler(cargo)
            if newState.lower() in self.endState:
                print("Reached ", newState)
                break
            else:
                handler = self.handler[newState.lower()]
